package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
	"tino_manager/public"
)

type UserController struct {
}

func UserRegister(group *gin.RouterGroup) {
	user := &UserController{}
	//微信用户登录或注册
	group.POST("/login", user.Login)
	//微信用户获取详情
	group.GET("/detail", middleware.WeAppMiddleware(), user.Detail)
	//微信用户修改个人资料
	group.POST("/update", middleware.WeAppMiddleware(), user.Update)
	//微信用户列表
	group.GET("/page", middleware.WeAppMiddleware(), user.Page)
	//修改用户状态
	group.POST("/update_status", middleware.WeAppMiddleware(), user.UpdateStatus)
	//开通或关闭消息提醒
	group.POST("/switch_message_status", middleware.WeAppMiddleware(), user.SwitchMessage)
	//获取消息提醒状态
	group.GET("/message_status", middleware.WeAppMiddleware(), user.GetMessageStatus)
}

// Login 用户登录
func (u *UserController) Login(c *gin.Context) {
	params := &dto.UserLoginAndRegister{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		fmt.Println(err, 1)
		middleware.ResponseError(c, 500, errors.New("登录失败"), true)
		return
	}
	appId := lib.GetStringConf("base.weapp.appId")
	appSecret := lib.GetStringConf("base.weapp.appSecret")
	err, resp := public.LoadUserOpen(appId, appSecret, params.Code)
	if err != nil {
		fmt.Println(err, 2)
		middleware.ResponseError(c, 500, errors.New("登录失败"), true)
		return
	}

	user := &dao.User{}
	if params.PhoneCode != "" {
		err, res := public.LoadUserPhone(appId, appSecret, params.PhoneCode)
		if err != nil {
			fmt.Println(err, 3)
			middleware.ResponseError(c, 500, errors.New("登录失败"), true)
			return
		}
		resp.Phone = res.PhoneInfo.PurePhoneNumber
	}
	if result := tx.Where(map[string]interface{}{
		"open_id": resp.OpenId,
	}).First(user); result.RowsAffected != 0 {
		if user.Status == 1 {
			middleware.ResponseError(c, 503, errors.New("当前账号已被限制登录,请联系客服"), true)
			return
		}
		if user.IsDelete == 1 {
			middleware.ResponseError(c, 503, errors.New("当前账号已被删除,请联系客服"), true)
			return
		}
		if user.UserName == "" && params.UserName != "" {
			user.UserName = params.UserName
		}
		if user.HeadImage == "" && params.HeadImage != "" {
			user.HeadImage = params.HeadImage
		}
		if resp.Phone != "" {
			user.Phone = resp.Phone
		}
		tx.Model(&dao.User{}).Where("id = ?", user.Id).Updates(user)
	} else {
		//新用户
		user = &dao.User{
			OpenId:    resp.OpenId,
			HeadImage: params.HeadImage,
			UserName:  params.UserName,
			Phone:     resp.Phone,
		}
		if err := user.Save(c, tx); err != nil {
			fmt.Println(err, 4)
			middleware.ResponseError(c, 503, errors.New("登录失败"), true)
			return
		}
	}
	middleware.ResponseSuccess(c, user.OpenId, false)
}
func (u *UserController) Update(c *gin.Context) {
	params := &dto.UserUpdateInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, errors.New("修改用户信息失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("修改用户信息失败"), true)
		return
	}
	user := &dao.User{
		UserName:  params.UserName,
		HeadImage: params.HeadImage,
		DeptName:  params.DeptName,
		Phone:     params.Phone,
		Name:      params.Name,
		Duties:    params.Duties,
	}
	if result := tx.Model(&dao.User{}).Where("id = ?", params.Id).Updates(user); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("修改用户信息失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (u *UserController) UpdateStatus(c *gin.Context) {
	params := &dto.UserUpdateStatusInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("修改用户信息失败"), true)
		return
	}
	user := &dao.User{
		Status: params.Status,
	}
	if result := tx.Model(&dao.User{}).Where("id = ?", params.Id).Select("status").Updates(user); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (u *UserController) SwitchMessage(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	params := &dto.SwitchMessageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.User{}).Where("open_id = ?", value).Update("open_message_status", params.OpenMessageStatus); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (u *UserController) Detail(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	params := &dto.UserDetailInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	user := &dao.User{}
	queryMap := map[string]interface{}{}
	if params.Id != "" {
		queryMap["id"] = params.Id
	} else {
		queryMap["open_id"] = value
	}
	if result := tx.Where(queryMap).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	middleware.ResponseSuccess(c, user, true)
}
func (u *UserController) Page(c *gin.Context) {
	params := &dto.UserPageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.User
	query := tx.WithContext(c).Model(&dao.User{}).Where("is_delete=0").Order("create_at desc")
	if params.Type == "1" {
		query = query.Where("status = 0")
	}
	if params.Type == "2" {
		query = query.Where("status = 1")
	}
	if params.KeyWord != "" {
		query = query.Where("user_name LIKE ? OR phone LIKE ?", "%"+params.KeyWord+"%", "%"+params.KeyWord+"%")
	}
	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败"), true)
		return
	}
	out := &dto.UserPageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.UserInfo{
			Id:            fmt.Sprintf("%d", item.Id),
			UserName:      item.UserName,
			OpenId:        item.OpenId,
			HeadImage:     item.HeadImage,
			MessageOpenId: item.MessageOpenId,
			Phone:         item.Phone,
			DeptName:      item.DeptName,
			Status:        item.Status,
			Name:          item.Name,
			Duties:        item.Duties,
			IsDelete:      item.IsDelete,
			CreatedAt:     item.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:     item.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, true)
}
func (u *UserController) GetMessageStatus(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	params := &dto.GetMessageStatusInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	appId := lib.GetStringConf("base.message.appId")
	appSecret := lib.GetStringConf("base.message.appSecret")
	err, resp := public.LoadMessageOpen(appId, appSecret, params.Code)
	if err != nil {
		fmt.Println(err)
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")

	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	user := &dao.User{}
	if result := tx.Where("open_id = ?", value).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	if result := tx.Model(user).Where("open_id = ?", value).Update("message_open_id", resp.OpenId); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	middleware.ResponseSuccess(c, user, true)
}
